from setuptools import setup, find_packages
import os
import subprocess
import fnmatch
import glob

# 获取 Tesseract 库路径
def find_library(name):
    """查找库文件"""
    patterns = [
        f"/usr/local/lib/lib{name}*.dylib",
        f"/opt/homebrew/lib/lib{name}*.dylib",
        f"/usr/local/opt/tesseract/lib/lib{name}*.dylib",
        f"/opt/homebrew/opt/tesseract/lib/lib{name}*.dylib",
    ]
    
    try:
        # 如果是 tesseract，添加 brew 路径
        if name == 'tesseract':
            result = subprocess.run(['brew', '--prefix', 'tesseract'], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                brew_prefix = result.stdout.strip()
                patterns.append(os.path.join(brew_prefix, 'lib', f'lib{name}*.dylib'))
        
        # 如果是 lept，尝试在 tesseract 依赖目录中查找
        elif name == 'lept':
            result = subprocess.run(['brew', '--prefix', 'tesseract'], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                tesseract_prefix = result.stdout.strip()
                deps_dir = os.path.dirname(tesseract_prefix)
                for root, _, files in os.walk(deps_dir):
                    for file in files:
                        if file.startswith('liblept') and file.endswith('.dylib'):
                            return os.path.join(root, file)
    except:
        pass
    
    # 查找库文件
    for pattern in patterns:
        try:
            files = glob.glob(pattern)
            if files:
                return os.path.realpath(files[0])
        except:
            continue
    
    return None

# 获取框架列表
frameworks = []
tesseract_lib = find_library('tesseract')
leptonica_lib = find_library('lept')

if tesseract_lib:
    frameworks.append(tesseract_lib)
if leptonica_lib:
    frameworks.append(leptonica_lib)

APP = ['contract_renamer/main.py']
DATA_FILES = [
    ('styles', ['contract_renamer/styles/light_theme.qss',
                'contract_renamer/styles/dark_theme.qss']),
    ('resources', ['contract_renamer/resources/icon.png']),
    ('tessdata', ['/usr/local/share/tessdata/chi_sim.traineddata']),
]

OPTIONS = {
    'argv_emulation': False,
    'packages': find_packages() + [
        'PySide6',
        'pytesseract',
        'cv2',
        'darkdetect',
        'baidu-aip',
        'numpy',
        'PIL',
    ],
    'includes': [
        'shiboken6',
        'PySide6.QtCore',
        'PySide6.QtGui',
        'PySide6.QtWidgets',
    ],
    'excludes': [
        'tkinter',
        'matplotlib',
        'PyQt5',
        'setuptools',
        'pip',
        'packaging',  # 避免packaging包的冲突
    ],
    'resources': [
        'contract_renamer/styles',
        'contract_renamer/resources',
    ],
    'iconfile': 'contract_renamer/resources/icon.icns',
    'plist': {
        'CFBundleName': 'Contract Renamer',
        'CFBundleDisplayName': 'Contract Renamer',
        'CFBundleIdentifier': 'com.yourdomain.contractrenamer',
        'CFBundleVersion': '1.0.0',
        'CFBundleShortVersionString': '1.0.0',
        'LSMinimumSystemVersion': '10.12',
        'NSHighResolutionCapable': True,
        'CFBundleIconFile': 'icon.icns',
    },
    'frameworks': frameworks,
    'strip': True,  # 减小文件大小
    'optimize': 2,  # 优化字节码
}

setup(
    name="Contract Renamer",
    version="1.0.0",
    description="Contract File Renaming Tool",
    author="Your Name",
    author_email="your.email@example.com",
    packages=find_packages(),
    app=APP,
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)